<?php
/**
 * Représente un document envoyé par un utilisateur
 *
 * @author Kévin Fauconnet (31/07/2013)
 */
 
class Document extends SimpleModel {
	
	public $id_document;
	public $titre;
	public $description;
	public $type_partage;
	
	public $filename;
	public $id_user;
	public $last_update;
	
	public $filepath;
	public $user;
	
	
	public function sqltable() { return "documents"; }
	public function schema() { return array(
		'id_document' 			=> array('primarykey' => true, 'type' => 'int'),
		'titre' 				=> 'string(255)',
		'description'			=> 'string(255)',
		'type_partage' 			=> 'int',
		'filename'				=> 'string(255)',
		'filepath'				=> 'string(255)',
		'id_user'				=> 'int',
		'last_update' 			=> 'datetime'
	);}
	
	/**
	 * Crée un nouvel objet
	 */	
	public function __construct($param = 0) {
		$this->id_document = 0;
		$this->titre = "";
		$this->description = "";
		$this->type_partage = 0;
		
		$this->filename = "";
		$this->filepath = "";
		$this->id_user = 0;
		$this->last_update = null;

		$this->init($param);

	}
	
	/**
	 * Sauvegarde l'objet, et met à jour l'attribut last_update
	 */	
	public function save($options = array()) {
		$this->last_update = date('d/m/Y H:i:s');

		return parent::save($options);
	}
	
	/**
	 * Remplit l'objet depuis les résultats d'un PDOStatement
	 */
	public function fromStatement($rowFetched, $st) {
		parent::fromStatement($rowFetched);
		
		if (!empty($rowFetched['nom'])) {
			require_once('user.class.php');
			$u = new User();
			$u->init($st);
			$this->user = $u;
		}
	}	
	
	/**
	 * Construit la requête de documents et l'exécute
	 *
	 * Options possible:
	 * - id_user: uniquement un ensemble d'ids
	 *
	 * @param $options Array options
	 * @return PDOStatement le statement lié à la requête
	 */		
	public static function buildQueryDocuments($options = array()) {
		
		$sql = "SELECT * FROM documents";
		
		if (!empty($options['count'])) {
			$sql = "SELECT COUNT(*) FROM documents";
		}
		
		else if (!empty($options['withUser'])) {
			$sql .= " LEFT JOIN users ON users.id_user = documents.id_user";
		}
		
		$where = array();
		
		if (!empty($options['id_user'])) {
			$where[] = array('AND', 'documents.id_user = ?', $options['id_user']);
		}
		if (!empty($options['type_partage'])) {
			$where[] = array('AND', 'documents.type_partage = ?', $options['type_partage']);
		}
		
		if (!empty($options['keywords'])) {
			$keywords = "%".$options['keywords']."%";
			$where[] = array('AND', 'documents.titre LIKE ? OR documents.description LIKE ?', array($keywords, $keywords));
		}
		$queryOptions = array(
			'query' => $sql,
			'where' => $where
		);
		if (empty($options['count'])) {
			$queryOptions += array(
				'orderby' => 	self::getOption($options, 'orderby', 'last_update'),
				'limit' => 		self::getOption($options, 'limit'),
				'offset' => 	self::getOption($options, 'offset'),
				'page' => 		self::getOption($options, 'page')
			);
		}
		
		return self::buildQuery($queryOptions);
	}
	
	/**
	 * Renvoie le total de documents
	 * Options possible:
	 * - id_user: uniquement un ensemble d'ids
	 *
	 * @param $options Array options
	 * @return Array<int> liste d'id_translation
	 */		
	public static function countDocuments($options = array()) {
	
		$options['count'] = true;
		
		$st = self::buildQueryDocuments($options);
		$total = $st->fetchOne('int');
		return $total;
	}
	
	/**
	 * Renvoie une liste de documents
	 * Options possible:
	 * - id_user: uniquement un ensemble d'ids
	 * - withUser: (boolean) permet de récupérer les données de l'utilisateur associé (jointure)
	 * - orderby
	 * - limit
	 * - offset
	 * - page
	 *
	 * @param $options Array options
	 * @return Array<int> liste d'id_translation
	 */		
	public static function getDocuments($options = array()) {
		$st = self::buildQueryDocuments($options);
		
		$results = array();

		while ($st->fetch()) {
			$results[] = new self($st);
		}
		return $results;
	}
	
	/**
	 * Renvoie le type du document
	 */
	public function getFileType() {
		require_once(HELPER_PATH.'file.helper.php');

		$ext = strtolower(file_get_extension($this->filepath));
		$type = "file";
		switch($ext) {
			case ".doc":
			case ".docx":
			case ".odf":
				$type = "word";
				break;
			
			case ".pdf":
				$type = "pdf";
				break;
			case ".xls":
			case ".xlsx":
			case ".ods":
				$type = "excel";
				break;
		}
		return $type;
	}
	
}
?>